<template>
  <div class="book-detail-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      left-arrow
      :title="bookName"
      @click-left="goBack"
    />

    <!-- 账本概览卡片 -->
    <div class="book-card">
      <div class="book-header">
        <div class="book-icon">
          <van-icon :name="bookIcon" size="32" :class="`icon-${bookType}`" />
        </div>
        <div class="book-info">
          <div class="book-title">{{ bookName }}</div>
          <div class="book-desc">{{ bookDesc }}</div>
        </div>
      </div>
      <div class="book-stats">
        <div class="stat-item">
          <div class="stat-label">总收入</div>
          <div class="stat-value income-color">¥{{ totalIncome }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">总支出</div>
          <div class="stat-value expense-color">¥{{ totalExpense }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">结余</div>
          <div class="stat-value balance-color">¥{{ balance }}</div>
        </div>
      </div>
    </div>

    <!-- 账本明细列表 -->
    <div class="record-list">
      <div class="list-header">
        <span class="header-title">账本明细</span>
      </div>
      
      <!-- 收支分类标签 -->
      <div class="filter-tabs">
        <van-tabbar v-model="activeTab" line-width="20" active-color="#FFD814" inactive-color="#999">
          <van-tabbar-item name="all">全部</van-tabbar-item>
          <van-tabbar-item name="income">收入</van-tabbar-item>
          <van-tabbar-item name="expense">支出</van-tabbar-item>
        </van-tabbar>
      </div>
      
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多记录了"
        @load="getRecords"
      >
        <van-cell
          v-for="item in filteredRecords"
          :key="item.id"
          :title="item.remark"
          :label="item.date"
          :value="formatMoney(item)"
          :class="item.type === 2 ? 'income-record' : 'expense-record'"
        >
          <template #icon>
            <van-icon 
              :name="item.type === 2 ? 'arrow-up' : 'arrow-down'" 
              :color="item.type === 2 ? '#07c160' : '#ff4d4f'"
            />
          </template>
          <template #extra>
            <span class="record-type">{{ getTypeName(item.category) }}</span>
          </template>
        </van-cell>
        
        <!-- 空状态 -->
        <div v-if="filteredRecords.length === 0 && !loading" class="empty-records">
          <van-empty description="暂无记录" />
        </div>
      </van-list>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { 
  NavBar, Icon, List, Cell, Tabbar, TabbarItem, 
  Empty, showToast
} from 'vant';
import { getAccountById, getBillDetail } from '@/api/index.js';

const router = useRouter();
const route = useRoute();

// 账本ID
const accountId = ref(null);
// 账本信息
const accountInfo = ref(null);

// 状态管理
const records = ref([]);
const loading = ref(false);
const finished = ref(false);
const currentPage = ref(1);
const activeTab = ref('all'); // 收支筛选标签

// 账本类型映射
const bookTypeMap = {
  business: { 
    name: '生意账本', 
    desc: '生意经营专用账本', 
    icon: 'shop-o', 
    types: {1: '销售收入', 2: '采购成本', 3: '运营费用', 4: '其他收入'}
  },
  expense: { 
    name: '报销账本', 
    desc: '适合记录报销账目', 
    icon: 'gold-coin-o',
    types: {1: '交通费用', 2: '餐饮费用', 3: '住宿费用', 4: '办公费用'}
  },
  company: { 
    name: '公司账本', 
    desc: '管理公司采购必备', 
    icon: 'bag-o',
    types: {1: '设备采购', 2: '办公用品', 3: '薪资支出', 4: '服务收入'}
  },
  team: { 
    name: '团队账本', 
    desc: '班费/团建经费专属', 
    icon: 'friends-o',
    types: {1: '成员缴费', 2: '活动支出', 3: '物资采购', 4: '剩余退款'}
  },
  wechat: { 
    name: '微商账本', 
    desc: '代购卖货账目', 
    icon: 'wap-home-o',
    types: {1: '销售收款', 2: '进货成本', 3: '快递费用', 4: '平台佣金'}
  },
  custom: { 
    name: '自定义账本', 
    desc: '自定义你的专属账本', 
    icon: 'edit',
    types: {1: '其他收入', 2: '其他支出', 3: '转账', 4: '投资'}
  }
};

// 路由参数获取
accountId.value = route.query.id;

// 账本信息计算属性
const bookType = computed(() => {
  if (!accountInfo.value) return 'custom';
  const idMap = {
    1: 'business',
    2: 'expense',
    3: 'company',
    4: 'team',
    5: 'wechat',
    6: 'custom'
  };
  return idMap[accountInfo.value.categoryId] || 'custom';
});

const bookInfo = computed(() => bookTypeMap[bookType.value] || bookTypeMap.custom);
const bookName = computed(() => accountInfo.value?.remark || bookInfo.value.name);
const bookDesc = computed(() => accountInfo.value?.type || bookInfo.value.desc);
const bookIcon = computed(() => bookInfo.value.icon);
const typeMap = computed(() => bookInfo.value.types);

// 类型列数据 (修复picker组件的columns格式)
const typeColumns = computed(() => {
  return Object.entries(typeMap.value).map(([id, name]) => ({
    text: name,
    value: parseInt(id)
  }));
});

// 统计数据计算
const totalIncome = computed(() => {
  const sum = records.value
    .filter(item => item.type === 2) // 2=收入
    .reduce((total, item) => total + Number(item.amount || 0), 0);
  return sum.toFixed(2);
});

const totalExpense = computed(() => {
  const sum = records.value
    .filter(item => item.type === 1) // 1=支出
    .reduce((total, item) => total + Number(item.amount || 0), 0);
  return sum.toFixed(2);
});

const balance = computed(() => {
  return (Number(totalIncome.value) - Number(totalExpense.value)).toFixed(2);
});

// 筛选记录
const filteredRecords = computed(() => {
  if (activeTab.value === 'all') return records.value;
  if (activeTab.value === 'income') return records.value.filter(item => item.type === 2);
  if (activeTab.value === 'expense') return records.value.filter(item => item.type === 1);
  return [];
});

// 获取记录类型名称（根据分类ID获取）
const getTypeName = (categoryId) => {
  return typeMap.value[categoryId] || `类型${categoryId}`;
};

// 获取账本信息
const loadAccountInfo = async () => {
  if (!accountId.value) {
    showToast('账本ID不存在');
    router.back();
    return;
  }
  
  try {
    const res = await getAccountById(accountId.value);
    console.log('获取账本信息响应:', res);
    
    // 响应拦截器已经提取了 data，直接使用即可
    if (res) {
      accountInfo.value = res;
      console.log('账本信息加载成功:', accountInfo.value);
    } else {
      showToast('获取账本信息失败');
      router.back();
    }
  } catch (error) {
    console.error('获取账本信息失败:', error);
    showToast(error.message || '获取账本信息失败');
    router.back();
  }
};

// 获取账本明细（获取所有记录）
const getRecords = async () => {
  if (finished.value || !accountId.value) return;
  loading.value = true;
  try {
    // 获取所有年份和月份的记录
    const allRecords = [];
    const currentYear = new Date().getFullYear();
    const currentMonth = new Date().getMonth() + 1;
    
    // 获取过去12个月的记录
    for (let i = 0; i < 12; i++) {
      let year = currentYear;
      let month = currentMonth - i;
      
      // 处理跨年的情况
      while (month <= 0) {
        month += 12;
        year -= 1;
      }
      
      try {
        const res = await getBillDetail({
          accountId: accountId.value,
          year: year,
          month: month
        });
        
        if (res && res.bills && res.bills.length > 0) {
          allRecords.push(...res.bills);
        }
      } catch (err) {
        console.log(`获取${year}年${month}月记录失败:`, err);
      }
    }
    
    // 按日期倒序排列
    allRecords.sort((a, b) => {
      const dateA = new Date(a.date);
      const dateB = new Date(b.date);
      return dateB - dateA;
    });
    
    console.log('获取账本明细总数:', allRecords.length);
    records.value = allRecords;
    finished.value = true;
  } catch (error) {
    console.error('获取记录失败:', error);
    showToast('获取记录失败，请重试');
    finished.value = true;
  } finally {
    loading.value = false;
  }
};


// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 格式化金额显示
const formatMoney = (item) => {
  // type: 1=支出, 2=收入
  return `${item.type === 2 ? '+' : '-'}¥${Number(item.amount || 0).toFixed(2)}`;
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 页面加载时获取数据
onMounted(async () => {
  await loadAccountInfo();
  getRecords();
});
</script>

<style scoped>
.book-detail-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 账本卡片样式 */
.book-card {
  background-color: #fff;
  border-radius: 12px;
  margin: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.book-header {
  display: flex;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f5f5f5;
}

.book-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  background-color: #f7f8fa;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

/* 图标颜色 */
.icon-business { color: #07c160; }
.icon-expense { color: #ff976a; }
.icon-company { color: #666; }
.icon-team { color: #1989fa; }
.icon-wechat { color: #07c160; }
.icon-custom { color: #ff976a; }

.book-info {
  flex: 1;
}

.book-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.book-desc {
  font-size: 14px;
  color: #999;
  margin-top: 4px;
}

.book-stats {
  display: flex;
  padding: 16px 20px;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 16px;
  font-weight: 500;
}

.income-color { color: #07c160; }
.expense-color { color: #ff4d4f; }
.balance-color { color: #333; }

/* 明细列表样式 */
.record-list {
  margin: 0 16px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-top: 10px;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 筛选标签样式 */
.filter-tabs {
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 10px;
}

/* 记录样式 */
.income-record {
  --van-cell-value-color: #07c160;
}

.expense-record {
  --van-cell-value-color: #ff4d4f;
}

.van-cell {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 10px;
}

.record-type {
  font-size: 12px;
  color: #999;
  margin-right: 16px;
}

/* 空状态 */
.empty-records {
  padding: 50px 0;
  text-align: center;
}

/* 适配Vant组件样式 */
:deep(.van-tabbar) {
  height: auto;
  padding: 8px 0;
}

:deep(.van-tabbar-item) {
  padding: 6px 0;
}

</style>